import * as systemService from '../../services/system';
import {routerRedux} from 'dva/router';

export default {
  namespace: 'role',
  state:{
    roles:[],
    roleResource:[],
    selectRoleresource:[],
    selectRow:undefined,
  },
  reducers: {
    updateRoles(state, {payload}) {
      const newstate = state;
      newstate.roles = payload;
      return newstate;
    },
    updateRoleResource(state, {payload}) {
      const newstate = state;
      newstate.roleResource = payload.allResources;
      const selectIds=[];
      for(const r of payload.roleResources){
        selectIds.push(r.id+'');
      }
      newstate.selectRoleresource = selectIds;
      return newstate;
    },
    updateCheckedKeys(state, {payload}) {
      const newstate = state;
      newstate.selectRoleresource = payload;
      return newstate;
    },
    updateSelectRow(state,{payload}){
      const newstate = state;
      newstate.selectRow = payload;
      return newstate;
    },
  },
  effects: {
    *getAllRoles({payload}, {call, put}) {
      const {data} = yield call(systemService.getAllRoles);
      yield put({type: 'updateRoles', payload: data});
    },
    *deleteRole({payload}, {call, put}) {
      yield call(systemService.deleteRoles,payload);
      yield put({type: 'getAllRoles'});
    },
    *addOrUpdateRole({payload}, {call, put}) {
      const {data} = yield call(systemService.addOrUpdateRole,payload);
      yield put({type: 'getAllRoles'});
      yield put({type: 'updateSelectRow',payload:data});
    },
    *getRoleResource({payload}, {call, put}) {
      const {data} = yield call(systemService.getRoleResource,payload);
      yield put({type: 'updateRoleResource',payload:data});
    },
    *updateCheckedKey({payload}, {call,put}) {
      let checkeds=[];
      if(payload.checkedKeys instanceof  Array){
        checkeds=payload.checkedKeys;
      }else{
        checkeds=payload.checkedKeys.checked;
      }
      const rebind={};
      rebind.roleId=payload.roleId;
      rebind.resourceIds=checkeds;
      yield call(systemService.reBindRoleResource,rebind);
      yield put({type: 'updateCheckedKeys',payload:payload.checkedKeys});
    },
  },
  subscriptions: {

  },

}
